package com.atguigu.gulimall.coupon.service.impl;

import com.atguigu.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.atguigu.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAmount;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.coupon.dao.SeckillSessionDao;
import com.atguigu.gulimall.coupon.entity.SeckillSessionEntity;
import com.atguigu.gulimall.coupon.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    SeckillSkuRelationService relationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLatest3DaysSession() {
        // 计算最近3天
        LocalDate now = LocalDate.now();
        LocalDate latest3Day = now.plusDays(3);

        LocalDateTime startTime = LocalDateTime.of(now, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(latest3Day, LocalTime.MAX);
        // 格式化时间
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startTimeFormat = startTime.format(pattern);
        String endTimeFormat = endTime.format(pattern);
        List<SeckillSessionEntity> sessionEntityList = list(new QueryWrapper<SeckillSessionEntity>()
                .between("start_time", startTimeFormat, endTimeFormat));

        if (!CollectionUtils.isEmpty(sessionEntityList)) {
            for (SeckillSessionEntity seckillSessionEntity : sessionEntityList) {
                // 查询关联关系
                Long sessionEntityId = seckillSessionEntity.getId();
                List<SeckillSkuRelationEntity> relationEntityList = relationService.list(
                        new QueryWrapper<SeckillSkuRelationEntity>()
                                .eq("promotion_session_id", sessionEntityId)
                );
                seckillSessionEntity.setRelationSkus(relationEntityList);
            }
        }
        return sessionEntityList;
    }

}